﻿@using CnGalWebSite.DataModel.ViewModel.Others;
@using System.Collections.Concurrent;
@inject ISettingService _settingService
@inject IDialogBoxService _dialogBoxService
@inject ILive2DService _live2DService
@implements IDisposable


<div class="@($"kanban-dialogbox {(_sleep?"d-none":"")}")" id="kanban-dialogbox" style="@_settingService.Setting.DialogBox.GetStyles()">
    <MDCard Style="@($"width: fit-content;{((_show && !_settingService.Setting.DialogBox.Hide)?"":"opacity: 0;")}")">
        <MDCard Style="@_settingService.Setting.DialogBox.GetContentStyles()">
            <ImageCard />
            <div class="content-card  pa-3">
                <div class="title-medium name">
                    @if (_type != IconType.None)
                    {
                        <CnGalWebSite.Shared.MasaComponent.Shared.Components.MasaIcon Type="_type" Color="@_color" Small="false" />
                    }
                    看板娘：
                </div>
                <div class="label-large text">
                    @($"『{_context}』")
                </div>
            </div>
            <CnGalWebSite.Components.Buttons.MasaButton Icon="@IconType.Close.ToIconString()" OnClick="Clean" />
        </MDCard>
    </MDCard>
</div>


@code {
    DialogBoxModel _model;
    ConcurrentQueue<DialogBoxModel> _queue = new ConcurrentQueue<DialogBoxModel>();

    /// <summary>
    /// 单位 0.1 秒
    /// </summary>
    int _delayTime = 0;
    bool _show;
    string _color;
    string _context;
    IconType _type;
    DateTime _lastEnd;
    bool _sleep;

    private System.Threading.Timer mytimer;

    protected override void OnInitialized()
    {
        _settingService.OnSettingChanged -= OnSettingChanged;
        _settingService.OnSettingChanged += OnSettingChanged;
    }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            //注册
            _dialogBoxService.Init(this);
            //启动定时器
            mytimer = new System.Threading.Timer(new System.Threading.TimerCallback(Send), null, 0, 100);
        }
    }
    public void Send(object o)
    {
        if ((DateTime.Now - _lastEnd).TotalSeconds < 0.5)
        {
            return;
        }
        if (_model != null)
        {
            _delayTime -= 100;
            if (_delayTime < 0)
            {
                _ = End();
                _lastEnd = DateTime.Now;
                return;
            }
            else
            {
                return;
            }
        }

        if (_queue.Count == 0)
        {
            if (!_sleep && (DateTime.Now - _lastEnd).TotalSeconds > 1)
            {
                _sleep = true;
                _ = InvokeAsync(StateHasChanged);
                return;
            }
            return;
        }

        if (!_queue.TryDequeue(out DialogBoxModel model))
        {
            return;
        }

        _ = Start(model);
    }

    public async Task Start(DialogBoxModel model)
    {
        _sleep = false;
        if (string.IsNullOrWhiteSpace(model.Content) == false)
        {
            _show = true;
        }
        else
        {
            _show = false;
        }

        _model = model;
        _context = model.Content;
        _delayTime = 1000 + model.Content.Length * 200;
        //动作
        if (model.Motion >= 0)
        {
            await _live2DService.SetMotion(model.MotionGroup, model.Motion);
        }
        else
        {
            await _live2DService.CleanMotion();
        }
        //表情
        if (string.IsNullOrWhiteSpace(model.Expression) == false)
        {
            await _live2DService.SetExpression(model.Expression);
        }
        else
        {
            await _live2DService.CleanExpression();
        }
        await Task.Delay(100);
        //生成图片
        await _live2DService.StartKanbanImageGeneration();
        //背景色
        if (model.Type == DialogBoxType.Text)
        {
            _color = "primary";
            _type = IconType.None;
        }
        else if (model.Type == DialogBoxType.Success)
        {
            _color = "success";
            _type = IconType.Success;
        }
        else if (model.Type == DialogBoxType.Warning)
        {
            _color = "warning";
            _type = IconType.Warning;
        }
        else if (model.Type == DialogBoxType.Info)
        {
            _color = "info";
            _type = IconType.Infor;
        }
        else if (model.Type == DialogBoxType.Error)
        {
            _color = "error";
            _type = IconType.Error;
        }
        //显示对话框
        await InvokeAsync(StateHasChanged);
    }

    public async Task End()
    {

        if (_queue.Count == 0)
        {
            if (string.IsNullOrWhiteSpace(_model?.Expression) == false)
            {
                await _live2DService.CleanExpression();
            }
            if (_model?.Motion >= 0)
            {
                await _live2DService.CleanMotion();
            }
            _show = false;
        }
        _model = null;
        await InvokeAsync(StateHasChanged);
    }

    public void Clean()
    {
        _delayTime = 0;
        _queue.Clear();
    }

    public void Add(DialogBoxModel model)
    {
        if (_queue.Count < 3)
        {
            _queue.Enqueue(model);
        }
    }

    public void ShowDialogBox(DialogBoxModel model)
    {
        if (model.Priority > 0)
        {
            Clean();
        }

        if (model.Priority < 0 && (_queue.Count > 0 || _show))
        {
            return;
        }

        Add(model);
    }

    public void OnSettingChanged()
    {
        StateHasChanged();
    }

    public void Dispose()
    {
        _settingService.OnSettingChanged -= OnSettingChanged;
        mytimer?.Dispose();
        GC.SuppressFinalize(this);
    }
}
